<template>
  <div class="box">
    <!-- 添加一个具有明确宽高的容器 -->
    <div ref="chartRef" class="echarts-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import contestQuery from "@/api/modules/contestQuery.ts";
import {userInfo} from "@/stores/userinfo.ts";

const userStore = userInfo();
const chartRef = ref<HTMLElement>();
let myChart: echarts.ECharts | null = null;

onMounted(async () => { // 改为异步函数
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);

    // 新增数据请求
    try {
      // 根据教师名字查询考试情况
      const { data } = await contestQuery.queryContestByName(userStore.userInfo.userName)
      console.log(data)

      const option = {
        title: {
          text: '考试情况统计'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['考试人数', '通过人数']
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.contestName) // 提取所有考试名称
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '考试人数',
            type: 'line',
            data: data.map(item => item.participantCount), // 修正字段名
            itemStyle: {
              color: '#5470C6'
            }
          },
          {
            name: '通过人数',
            type: 'line',
            data: data.map(item => item.passedCount), // 修正字段名
            itemStyle: {
              color: '#91CC75'
            }
          }
        ]
      };

      myChart.setOption(option);
    } catch (error) {
      console.error('获取数据失败:', error);
    }

    // 添加窗口 resize 监听
    window.addEventListener('resize', () => myChart?.resize());
  }
});

onBeforeUnmount(() => {
  // 组件卸载时销毁实例
  myChart?.dispose();
  window.removeEventListener('resize', () => myChart?.resize());
});
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 400px; /* 根据实际需求调整高度 */
}
</style>